<?php
namespace app\repository;

use \PDO;
use app\Utils;

/**
 * 数据库操作基础类
 * */
abstract class BaseRepository {
    /**
     * 获取实体
     * */
    abstract function getEntity();

    /**
     * 获取对应的数据表
     * */
    abstract function getTable();

    abstract function getManyToOne();

    /**
     * 获取字段
     * */
    public function getFields($enableAs = false, $joinField = null) {
        // 初始化几个变量
        $entity = $this->getEntity();
        // 开始获取字段
        $objectFields = get_object_vars($entity);
        $table = is_null($joinField) ? $this->getTable() : $joinField;
        $fields = [];
        foreach($objectFields as $key => $value) {
            if (!is_object($value)) {
                $snakeCaseKey = Utils::pascalCaseToSnakeCase($key);
                $temp = "`$table`.`$snakeCaseKey`";

                // 是否加入as
                if ($enableAs) {
                    $temp .= " as `$table.$snakeCaseKey`"; 
                }
                array_push($fields, $temp);
            }
        }

        $manyToOne = $this->getManyToOne();
        $result = implode(", ", $fields);
        if (!empty($manyToOne)) {
            foreach($manyToOne as $joinField => $joinRepository) {
                $result .= ', ' . $joinRepository->getFields(true, $joinField);
            }
        }

        return $result;
    }

    /**
     * 
     * @param debug 是否为调试模式
     * @return 成功：数据库连接信息；失败：null
     * */
    static function getConn($debug = false) {
        $servername = "mysql.5.6";
        $dbname = "yunzhi";
        $dbusername = "root";
        $password = "";
         
        try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbname", $dbusername, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $conn;
        }
        catch(PDOException $e)
        {
            if ($debug) {
                echo $e->getMessage();
            }
            return null;
        }
    }

    /**
     * 获取查询中的from字段
     * */
    protected function getQueryFrom() {
        $table = $this->getTable();
        $result = " `$table` ";
        $manyToOne = $this->getManyToOne();
        if (!empty($manyToOne)) {
            foreach($manyToOne as $joinField => $joinRepository) {
                $joinTable = $joinRepository->getTable();
                $joinFieldId = $joinField . '_id';
                $result .= "LEFT JOIN `$joinTable` AS `$joinField` ON `$table`.`$joinFieldId` = `$joinField`.`id` ";
            }
        }
        return $result;
    }
}